﻿$.MGJ.AllotCode = [];
(function () {
    var _this = $.MGJ.AllotCode;
    $.extend($.MGJ.AllotCode, {
        Dialog_AllotCodeObj: null,
        Dialog_AllotCode: function () {
            this.Dialog_AllotCodeObj = $.L.dialog({
                url: ACTION_URL("AllotCodeAdd", "CodeManage"),
                title: "码分配新增",
                width: 800,
                height: "auto",
                buttons: {
                    "button_save": {
                        type: 'primary',
                        text: '保存',
                        click: function () {
                            var bootstrapValidator = $("#form_AllotCodeAdd").data('bootstrapValidator').validate();
                            var StartCode = $("#StartCode").val()
                            var EndCode = $("#EndCode").val()
                            var Code = EndCode - StartCode
                            if (!bootstrapValidator.isValid()) {
                                $.L.msgError("请检查数据格式！");
                            }
                            else {
                                $(".btn-primary").attr("disabled", true);
                                _this.AllotSave();
                            }
                        }
                    },
                    "button_cancel": {
                        type: 'default',
                        text: '取消',
                        click: 'MODALMISS'
                    }
                }
            });
            //setTimeout(function () {
            //    _this.GetCurrentEnterpriseDirectSubLevel();
            //    _this.GetBatchList(0);
            //}, 500);
        },
        // 获取当前机构的直接子级
        GetCurrentEnterpriseDirectSubLevel: function () {
            $.L.ajaxHandle({
                url: ACTION_URL('GetCurrentEntepriseDirectSubLevel', 'CodeManage'),
                type: "GET",
                success: function (r) {
                    var option = r.length == 0 ? "<option value='0' selected >请先添加信息</option>" : "<option value='0' selected >--请选择--</option>";
                    $("#DirectSubLevel").children().remove();
                    $(r).each(function (i, ele) {
                        if (i == 0) {
                            _this.GetProductByEnterprise(ele.Code);
                        }
                        option = '<option value="' + ele.Code + '">' + ele.Name + '</option>'
                        $("#DirectSubLevel").append(option);
                    })
                }
            })
        },

        //获取所选机构的产品列表
        GetProductByEnterprise: function (enterpriseId) {

            var _enterpriseId = enterpriseId;
            if (!_enterpriseId) {
                _enterpriseId = $("#DirectSubLevel").val();
            }
            if (_enterpriseId) {
                $.L.ajaxHandle({
                    url: ACTION_URL('GetProductNameList', 'CodeManage'),
                    type: 'GET',
                    data: { enterpriseId: _enterpriseId },
                    success: function (r) {
                        $(r).each(function (i, ele) {
                            var option = r.length == 0 ? "<option value='0' selected >请先添加信息</option>" : "<option value='0' selected >--请选择--</option>";
                            option = '<option value="' + ele.Code + '">' + ele.Name + '</option>'
                            $("#ProductSelect").append(option);
                        })
                    }
                })
            }
        },
        dataModel: {
            AllotType: 0,
            BrandName: "123456",
            AllotCount: $("#AllotCount").val(),
            AllotCount2: $("#AllotCount2").val()
        },
        AllotSave: function () {
            var _e_id = $("#DirectSubLevel").val();
            var _e_name = $("#DirectSubLevel").find("option:selected").text();
            var _p_id = $("#ProductSelect").val();
            var _p_name = $("#ProductSelect").find("option:selected").text();
            var _p_size = $("#ProductSize").val();
            var _batch = $("#GenCodeBatch").val();
            var _batch_name = $("#GenCodeBatch").find("option:selected").text();
            var _startcode = Number($("#StartCode").val());
            var _endcode = Number($("#EndCode").val());
            var _AllotCount = $("#AllotCount").val();
            var _AllotCount2 = $("#AllotCount2").val();
            var HidCount = Number($("#HidCount").val());
            _this.dataModel.F_EnterpriseName = _e_id;
            _this.dataModel.T_EnterpriseId = _e_id;
            _this.dataModel.T_EnterpriseName = _e_name;
            _this.dataModel.ProductId = _p_id;
            _this.dataModel.AllotProductName = _p_name;
            _this.dataModel.ApplyProductSize = _p_size;
            _this.dataModel.AllotBatchId = _batch;
            _this.dataModel.AllotBatch = _batch_name;
            if (_this.dataModel.AllotType == 0) {
                _this.dataModel.StartCode = _startcode;
                _this.dataModel.EndCode = _endcode;
                _this.dataModel.AllotCount = _AllotCount;
                if (_startcode != 0 && _endcode != 0) {
                    var num = _endcode - _startcode
                    if (num < 0) {
                        $.L.msgError("结束码必须大于起始码！");
                        return;
                    }
                }
                if (_endcode > HidCount) {
                    $.L.msgError("结束码必须小于整批数量！");
                    return;
                }
            }
            if (_this.dataModel.AllotType == 1) {
                _this.dataModel.AllotCount = _AllotCount2;
            }

            var data = JSON.stringify({
                model: _this.dataModel,
                notSkip: true,
                isAdd: true
            });
            $.ajax({
                url: ACTION_URL("AllotCodeAddOp", "CodeManage"),
                contentType: "application/json",
                type: 'POST',
                datatype: 'json',
                data: data,
                success: function (r) {
                    if (r == true) {
                        _this.GetCurrentUserAllotList();
                        _this.Dialog_AllotCodeObj.close();
                        $.L.msgSuccess("分配完成");

                    } else {
                        $.L.msgWarning(r);
                    }
                }
            })
        },
        //设置分配方式
        SetAllotType: function (a) {
            _this.dataModel.AllotType = a;
        }
    });
})(jQuery);

(function () {
    var _this = $.MGJ.AllotCode;
    $.extend($.MGJ.AllotCode, {
        PageIndex: 1,
        PageSize: 10,
        AllotPagedList: null,
        SearchType: 0,//搜索状态 默认普通
        //获取用户的码分配与申请列表记录
        GetCurrentUserAllotList: function (pageindex) {
            _this.PageIndex = pageindex || 1;
            window.SearchKey = removeSpace($("#Nor_SerialNum").val());
            var _s_productName = "";
            var _t_e_name = "";
            var _verifieState = "";
            if (_this.SearchType == 1) {
                _s_productName = $("#SProductName").val();
                _t_e_name = $("#S_T_EName").val();
                _serialNum = $("#SSerialNum").val();
                _verifieState = $("#SVerifieState").val();
            }
            $.L.ajaxHandle({
                url: ACTION_URL("GetAllotCodePagedList", "CodeManage"),
                type: "GET",
                data: {
                    pageIndex: _this.PageIndex,
                    pageSize: _this.PageSize,
                    serialNum: window.SearchKey,
                    productName: _s_productName,
                    toEnterpriseName: _t_e_name,
                    verifieState: _verifieState
                },
                success: function (r) {
                    window.Temp_AllotPagedList = _this.AllotPagedList = r.PageData;
                    $("#OMID_left").L_bindingDataList(r);
                    $("#OMID_right").L_bindingDataList(r);
                    $("#tableList").L_bindingDataList(r);
                    $("#tableList .handleType").each(function () {
                        if($(this).text()=='未审核')
                        {
                            $(this).siblings('.AllotType').text('未审核');
                        }

                    })
                    $(".AllotProductName").each(function () {
                        if ($(this).text() == "--请选择--") {
                            $(this).html("")
                        }
                    }),
                    $(".StartCode").each(function () {
                        if ($(this).text() == 0) {
                            $(this).html("")
                        }
                    })
                    $(".EndCode").each(function () {
                        if ($(this).text() == 0) {
                            $(this).html("")
                        }
                    })
                }
            })
        },
        //查看
        Dialog_View: function (a) {
            _this.AllotType = 0;
            DataModel = _this.ReturnModelById(a);
            if (!DataModel) {
                $.L.msgWarning("当前无法执行该操作,请刷新后重试");
                return;
            }
            $.L.dialog({
                url: ACTION_URL("AllotCodeView", "CodeManage"),
                title: "码申请/分配查看",
                width: 800,
                height: 'auto',
                buttons: {
                    "button_cancel": {
                        type: 'default',
                        text: '关闭',
                        click: 'MODALMISS'
                    }
                }
            })
        },
        //审核
        IsPass: false,
        DataModel: null,
        VerifieBox: null,
        AllotType: 0,
        arr: [1, 2],
        Dialog_Verifie: function (a) {
            _this.AllotType = 0;
            DataModel = _this.ReturnModelById(a);
            arr = DataModel.CodeFunc.split(',');
            if (!DataModel) {
                $.L.msgWarning("当前无法执行该操作,请刷新后重试");
                return;
            }
            this.VerifieBox = $.L.dialog({
                url: ACTION_URL("AllotCodeVerifie", "CodeManage"),
                title: "码申请审核",
                width: 800,
                height: 'auto',
            });

            setTimeout(function () {
                if (arr.length == 1) {
                    if (arr[0] == 1)
                    { $('.CodeType[value=1]').attr('checked', true) }
                    else if (arr[0] == 2) {
                        $('.CodeType[value=2]').attr('checked', true)
                    }
                }
                else {
                    $('.CodeType').attr('checked', true)
                }

            }, 1000)

        },
        //关闭弹窗
        CloseDialog: function () {
            if (_this.VerifieBox) {
                _this.VerifieBox.close();
            }
        },
        //确认审核
        NextStep: function () {
            var allotid = $("#ID").val();
            var EID = $("#T_EntperiseId").val();
            var Count = $("#ApplyCount").val();
            var CodeTypes = $("#CodeFunc").val();
          
            $.L.ajaxHandle({
                url: ACTION_URL("Isadmin", "CodeManage"),
                type: "GET",
                data: { "EnterpriseId": 1 },
                success: function (r) {
                    if (r == 1) {
                        sessionStorage.setItem('allotid', allotid);
                        sessionStorage.setItem('EID', EID);
                        sessionStorage.setItem('Count', Count);
                        sessionStorage.setItem('CodeTypes', CodeTypes);
                        $.MGJ.RawCode.Dialog_BornCode(allotid, EID, Count, CodeTypes);
                        $.MGJ.AllotCode.CloseDialog()
                    }
                    else {
                        if ($("#NextStep").text() == "确认审核") {
                            _this.Save();
                        } else {
                            $("#VerifieView").hide("fast");
                            $("#TestContent").show("fast");
                            $("#PrevStep").show("fast");
                            $("#NextStep").text("确认审核");
                        }
                    }
                }
            })
        },
        //上一步
        PrevStep: function () {
            $("#NextStep").text("下一步");
            $("#VerifieView").show("fast");
            $("#TestContent").hide("fast");
            $("#PrevStep").hide("fast");
        },
        //不通过
        NotPass: function () {
            _this.IsPass = false;
            $("#NotPass").addClass("active");
            $("#Pass").removeClass("active");
            $("#PassContent").hide("fast");
            $("#NotPassContent").show("fast");
        },
        //通过
        Pass: function () {
            _this.GetBatchList(0);
            _this.IsPass = true;
            $("#Pass").addClass("active");
            $("#NotPass").removeClass("active");
            $("#NotPassContent").hide("fast");
            $("#PassContent").show("fast");
        },
        AllotType: 0,
        //按号段
        ByCodeNum: function (callBack) {
            _this.GetBatchList(0);
            this.AllotType = 0;
            $("#ByCodeNum").addClass("active");
            $("#ByFullPage").removeClass("active");
            $("#NeedStatEndCode").show("fast");
            $("#NeedStatEndCode2").hide("fast");
            $("#StartCode").val("");
            $("#EndCode").val("");
            $("#AllotCount").val("");
            if (callBack) { callBack(); }
        },
        //整版
        ByFullPage: function (callBack) {
            _this.GetBatchList(1);
            this.AllotType = 1;
            $("#ByFullPage").addClass("active");
            $("#ByCodeNum").removeClass("active");
            $("#NeedStatEndCode").hide("fast");
            $("#NeedStatEndCode2").show("fast");
            if (callBack && (typeof callBack) == "function") { callBack(); }
        },
        //获取可用批次
        GetBatchList: function (allotType) {
            $.L.ajaxHandle({
                url: ACTION_URL("GetGenCodeBatchList", "CodeManage"),
                type: "GET",
                data: { allotType: allotType },
                success: function (r) {
                    $("#GenCodeBatch").children().remove();
                    var first = "<option value='' selected >--请选择--</option>";
                    $("#GenCodeBatch").append(first);
                    $(r).each(function (i, ele) {
                        var option = '<option value="' + ele.Code + '">' + ele.Name + '</option>'
                        $("#GenCodeBatch").append(option);
                    })
                    if (r == 0) {
                        $.L.msgWarning("暂无可分配批次！");
                    }
                    //按整版分配 计算总数
                    if (allotType == 1) {
                        _this.ReturnSelectCount(2);
                    }
                }
            })
        },
        onBatchChange: function () {
            var type = _this.dataModel.AllotType;
            _this.ReturnSelectCount(type);
        },
        //保存
        Save: function () {
            if (_this.IsPass) {
                //通过保存
                //校验起始与结束码
                var bootstrapValidator = $("#form_AllotCodeAdd").data('bootstrapValidator').validate();//触发全部验证
                if (bootstrapValidator.isValid()) {
                    DataModel.AllotBatchId = $("#GenCodeBatch").val();
                    DataModel.AllotBatch = $("#GenCodeBatch").find("option:selected").text();
                    DataModel.StartCode = Math.abs(Number($("#StartCode").val()));
                    DataModel.EndCode = Math.abs(Number($("#EndCode").val()));
                    DataModel.HasVerifie = 1;
                   
                    if (DataModel.AllotType == 0) {
                        DataModel.AllotCount = $("#AllotCount").val();
                    }
                    else if (DataModel.AllotType == 1) {
                        DataModel.AllotCount = $("#AllotCount2").val();
                    }
               
                    DataModel.AllotType = this.AllotType;
                    var HidCount = Number($("#HidCount").val());

                    if (DataModel.AllotType == 0) {
                        
                        if (DataModel.StartCode != '' && DataModel.EndCode != '') {
                            var num = DataModel.EndCode - DataModel.StartCode
                            if (num < 0) {
                                $.L.msgError('结束码必须大于起始码!');
                                return
                            }
                        }
                        if (DataModel.EndCode > HidCount) {
                            $.L.msgError('结束码不能大于整批数量!');
                            return
                        }
                        var ApplyCount2 = $("#ApplyCount2").val();
                        var AllotCount = $("#AllotCount").val();
                        var num = ApplyCount2 - AllotCount
                        if (num > 0) {
                            $.L.msgError("分配数量不能小于申请数量！");
                            return
                        }
                        $.L.ajaxHandle({
                            url: ACTION_URL("AllotCodeAddOp", "CodeManage"),
                            data: DataModel,
                            success: function (r) {
                                if (r == true) {
                                    _this.GetCurrentUserAllotList();
                                    _this.CloseDialog();
                                    $.L.msgSuccess("操作成功！");
                                } else {
                                    $.L.msgWarning(r);
                                }
                            }

                        })
                    }
                    else if (DataModel.AllotType == 1) {
                        
                        var ApplyCount2 = $("#ApplyCount2").val();
                        var AllotCount2 = $("#AllotCount2").val();
                        var num = ApplyCount2 - AllotCount2
                        if (num > 0) {
                            $.L.msgError("分配数量不能小于申请数量！");
                            return
                        }

                        DataModel.AllotCount = $("#AllotCount2").val();
                        
                        $.L.ajaxHandle({
                            url: ACTION_URL("AllotCodeAddOp", "CodeManage"),
                            data: DataModel,
                            success: function (r) {
                                if (r == true) {
                                    _this.GetCurrentUserAllotList();
                                    _this.CloseDialog();
                                    $.L.msgSuccess("操作成功！");
                                } else {
                                    $.L.msgWarning(r);
                                }
                            }

                        })
                    }
                }
                else {
                    $.L.msgError("请检查数据格式！");
                }

            } else {
                $.L.msgConfirm("确认驳回该请求?", function () {
                    //不通过
                    $.L.ajaxHandle({
                        url: ACTION_URL('RefuseAllotCode', 'CodeManage'),
                        type: "GET",
                        data: { id: DataModel.ID, reason: $("#VerificationNotes").val() },
                        success: function () {
                            _this.GetCurrentUserAllotList(_this.PageIndex);
                            _this.CloseDialog();
                        }
                    })
                })
            }
        },
        //设置搜索方式
        SetSearchType: function () {
            if (_this.SearchType == 0) {
                _this.SearchType = 1;
            } else {
                _this.SearchType = 0;
            }
        },
        //导出EXCEL 
        ExprotExcel: function (ele) {
            var _serialNum = $("#Nor_SerialNum").val();
            var _s_productName = "";
            var _t_e_name = "";
            var _verifieState = "";
            if (_this.SearchType == 1) {
                _s_productName = $("#SProductName").val();
                _t_e_name = $("#S_T_EName").val();
                _serialNum = $("#SSerialNum").val();
                _verifieState = $("#SVerifieState").val();
            }
            $("input.AllClickChild:checked").each(function () {
                info.push($(this).attr('ID'));

            });
            if (info.length == 0) {
                $.L.msgError("请选择要导出的数据信息！");
                return
            }
            if (!$(ele).find('.no-result').hasClass('no-result')) {
                window.open(ACTION_URL("ExportExcelFromAllotCode", "CodeManage") + "?Key=" + info);
            }
            else {
                $.L.msgWarning('导出数据不能为空！')
            }
        }
    });
})(jQuery);
//other
(function () {
    var _this = $.MGJ.AllotCode;
    $.extend($.MGJ.AllotCode, {
        //返回审核状态
        ReturnVerifieState: function (a) {
            if (0 == a) {
                return "未审核";
            }
            if (1 == a) {
                return "审核通过";
            }
            if (2 == a) {
                return "审核驳回";
            }
            return "----";
        },
        //返回分配方式名称
        ReturnAllotTypeName: function (a) {
          
            if (0 == a) {
                return "号段分配";
            }
            if (1 == a) {
                return "整批分配";
            }
            if (2 == a) {
                return "手机码关联";
            }
            return "----";
        },
        //返回发起方式名称
        ReturnLaunchName: function (a) {
            if (!a) {
                return "----";
            }
            if (a.indexOf("MFP") != -1) {
                return "码分配";
            }
            if (a.indexOf("MSQ") != -1) {
                return "码申请";
            }
        },
        //返回显示按钮
        ReturnOpButton: function (a, b, c) {
            if (0 == a) {
                c[0].innerHTML = "<a onclick='$.MGJ.AllotCode.Dialog_Verifie(" + b.ID + ")'>审核</a>"
            } else if (1 == a || 2 == a) {
                c[0].innerHTML = "<a onclick='$.MGJ.AllotCode.Dialog_View(" + b.ID + ")'>查看</a>"
            }
        },
        //通过ID寻找实体模型
        ReturnModelById: function (id) {

            _this.AllotPagedList = _this.AllotPagedList || window.Temp_AllotPagedList;

            if (!_this.AllotPagedList || !id) {
                return null;
            }
            if (_this.AllotPagedList instanceof Array) {
                for (var item in _this.AllotPagedList) {
                    var _temp = _this.AllotPagedList[item];
                    if (_temp && _temp.ID === id) {
                        return _temp;
                    }
                }
            }
            return null;
        },
        //计算已选数量
        ReturnSelectCount: function (type) {
            var _batchNum = $("#GenCodeBatch").find("option:selected").text();
            if (_batchNum) {
                $.L.ajaxHandle({
                    url: ACTION_URL("GetWholeBatchCount", "CodeManage"),
                    type: "GET",
                    data: { batchNo: _batchNum },
                    success: function (r) {
                        $("#HidCount").val(r);
                        if (type == 0) {
                            var _startCode = Number($("#StartCode").val());
                            var _endCode = Number($("#EndCode").val());
                            if (_startCode != "" && _endCode != "") {
                                $("#AllotCount").val(parseInt(_endCode) - parseInt(_startCode) + 1);
                            }
                        } else {
                            //计算整版数量
                            if (r == 0) {
                                $("#AllotCount2").val("");
                            }
                            else {
                                $("#AllotCount2").val(r);
                            }
                        }
                    }
                })
            }
        }
    })
})(jQuery);